package ;
import js.Browser;
import js.html.CanvasElement;
import js.html.CanvasGradient;
import js.html.CanvasRenderingContext2D;
import js.html.Element;
import js.html.Image;
import js.html.ImageElement;
import js.JQuery;
import js.JQuery.JQueryHelper.*;

/**
 * ...
 * @author axel@cunity.me
 */
class Reflection
{
	public var element:Element;
	
	public function new(img:Image, height:Float, opacity:Float) 
	{
		var	cntx:CanvasRenderingContext2D, gradient:CanvasGradient;
		element = J(img).parent().append("<canvas class='reflection' style='position:absolute'/>").find(':last')[0];
		if (!Reflect.isFunction(untyped element.getContext) && JQuery.browser.msie)
		{
			element = J(img).parent().append("<img class='reflection' style='position:absolute'/>").find(':last')[0];
			var reflection:ImageElement = cast(element, ImageElement);	
			reflection.src = img.src;	
			untyped reflection.style.filter = "flipv progid:DXImageTransform.Microsoft.Alpha(opacity=" + (opacity * 100) + ", style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy=" + (reflHeight / imageHeight * 100) + ")";						
		}
		else
		{
			cntx = cast(element, CanvasElement).getContext("2d");
			try
			{
				J(element).attr( { width: img.width, height: height } );
				cntx.save();
				cntx.translate(0, img.height - 1);
				cntx.scale(1, -1);
				cntx.drawImage(img, 0, 0, img.width, img.height);
				cntx.restore();
				cntx.globalCompositeOperation = "destination-out";
				gradient = cntx.createLinearGradient(0, 0, 0, height);
				gradient.addColorStop(0, "rgba(255, 255, 255, " + (1 - opacity) + ")");
				gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
				cntx.fillStyle = gradient;
				cntx.fillRect(0, 0, img.width, height);
			}
			catch (e:Dynamic)
			{
				trace(e);
				return;
			}
		}
		J(element).attr( { alt:J(img).attr('alt'), title:J(img).attr('title') } );
		//<canvas class="reflection" style="position: absolute; left: 342px; top: 74.2525944666275px; width: 146.334368540005px; height: 25.6085144945009px;" width="320" height="56" alt="Natural Healthcare provides affordable treatment and additional income opportunities for farmers particularly in dry regions and on poor soils." title="Healing Herbs and Trees"></canvas>
	}
	
}